package com.sloth.bear.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sloth.bear.constant.ResultCode;
import com.sloth.bear.dto.entity.DocItem;
import com.sloth.bear.dto.request.DocItemRequest;
import com.sloth.bear.dto.vo.DocumentItemVo;
import com.sloth.bear.exception.BusinessException;
import com.sloth.bear.mapper.DocItemMapper;
import com.sloth.bear.mapper.DocMapper;
import com.sloth.bear.service.DocItemService;
import com.sloth.bear.util.AssertUtils;
import com.sloth.bear.util.BaseHelper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 文档子项服务实现类
 */
@RequiredArgsConstructor
@Service
public class DocItemServiceImpl extends ServiceImpl<DocItemMapper, DocItem> implements DocItemService {

    private final DocItemMapper documentItemMapper;
    private final DocMapper documentMapper;

    @Override
    public List<DocumentItemVo> getItemsByDocumentId(Long documentId) {
        LambdaQueryWrapper<DocItem> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DocItem::getDocumentId, documentId)
                .orderByDesc(DocItem::getIsTop)
                .orderByAsc(DocItem::getSortNo);

        List<DocItem> items = documentItemMapper.selectList(wrapper);
        return BaseHelper.r2t(items, DocumentItemVo.class);
    }

    @Override
    public DocumentItemVo getItemById(Long id) {
        DocItem item = documentItemMapper.selectById(id);
        if (item == null) {
            throw new BusinessException(ResultCode.BAD_REQUEST.getCode(), "文档子项不存在");
        }
        return BaseHelper.r2t(item, DocumentItemVo.class);
    }

    @Override
    public DocumentItemVo createItem(DocItemRequest request) {
        // 验证文档是否存在
        if (documentMapper.selectById(request.getDocumentId()) == null) {
            throw new BusinessException(ResultCode.BAD_REQUEST.getCode(), "关联的文档不存在");
        }

        // 验证名称和内容不能都为空
        boolean hasName = request.getName() != null && !request.getName().trim().isEmpty();
        boolean hasContent = request.getContent() != null && !request.getContent().trim().isEmpty();
        if (!hasName && !hasContent) {
            throw new BusinessException(ResultCode.BAD_REQUEST.getCode(), "子项名称和内容不能都为空，请至少填写一项");
        }

        DocItem item = new DocItem();
        item.setDocumentId(request.getDocumentId());
        item.setName(request.getName());
        item.setContent(request.getContent());
        item.setSortNo(request.getSortNo() != null ? request.getSortNo() : 0);
        item.setStarRating(request.getStarRating() != null ? request.getStarRating() : 0);
        item.setCompleted(request.getCompleted() != null ? request.getCompleted() : false);

        int result = documentItemMapper.insert(item);
        if (result <= 0) {
            throw new BusinessException(ResultCode.BAD_REQUEST.getCode(), "创建文档子项失败");
        }
        return BaseHelper.r2t(item, DocumentItemVo.class);
    }

    @Override
    public void updateItem(Long id, DocItemRequest request) {
        DocItem docItem = getEntity(id);

        // 验证文档是否存在
        if (documentMapper.selectById(request.getDocumentId()) == null) {
            throw new BusinessException(ResultCode.BAD_REQUEST.getCode(), "关联的文档不存在");
        }

        // 验证名称和内容不能都为空
        boolean hasName = request.getName() != null && !request.getName().trim().isEmpty();
        boolean hasContent = request.getContent() != null && !request.getContent().trim().isEmpty();
        if (!hasName && !hasContent) {
            throw new BusinessException(ResultCode.BAD_REQUEST.getCode(), "子项名称和内容不能都为空，请至少填写一项");
        }

        BeanUtils.copyProperties(request,docItem);
        boolean result = updateById(docItem);
        AssertUtils.isTrue(result, "更新文档子项失败");
    }

    private DocItem getEntity(Long id) {
        DocItem docItem = getById(id);
        AssertUtils.notNull(docItem, "文档子项不存在");
        return docItem;
    }

    @Override
    public DocumentItemVo toggleComplete(Long id) {
        DocItem existItem = documentItemMapper.selectById(id);
        if (existItem == null) {
            throw new BusinessException(ResultCode.BAD_REQUEST.getCode(), "文档子项不存在");
        }

        // 切换完成状态
        existItem.setCompleted(existItem.getCompleted() == null ? true : !existItem.getCompleted());

        int result = documentItemMapper.updateById(existItem);
        if (result <= 0) {
            throw new BusinessException(ResultCode.BAD_REQUEST.getCode(), "更新文档子项状态失败");
        }
        return BaseHelper.r2t(existItem, DocumentItemVo.class);
    }

    @Override
    public boolean deleteItem(Long id) {
        if (id == null) {
            throw new BusinessException(ResultCode.BAD_REQUEST.getCode(), "文档子项ID不能为空");
        }

        DocItem existItem = documentItemMapper.selectById(id);
        if (existItem == null) {
            throw new BusinessException(ResultCode.BAD_REQUEST.getCode(), "文档子项不存在");
        }

        int result = documentItemMapper.deleteById(id);
        if (result <= 0) {
            throw new BusinessException(ResultCode.BAD_REQUEST.getCode(), "删除文档子项失败");
        }
        return true;
    }
}